package com.expertria.glex.event;

import java.util.ArrayList;

 
public class Events {

	public static interface IEventListener {
		void onEvent(Event e);
	}

	public static interface IEventDispatcher {
		void addEventListener(String event, IEventListener e);

		void dispatch(String eventName, Object object);

		void dispose();

	}

	/**
	 * Base class for Events
	 * Inherit your custom events with this
	 * @author hushunjie
	 *
	 */
	public static class Event {
		private String eventName;
		private Object data;
		private Object source;

		private boolean _preventDefault = false;

		public static final String SUCCESS = "SUCCESS";
		public static final String FAILURE = "FAILURE";

		public Event(String eventName, Object data) {
			this(eventName, data, null);
		}

		public Event(String eventName, Object data, Object source) {
			super();
			this.eventName = eventName;
			this.data = data;
			this.source = source;
		}

		public String getEventName() {
			return eventName;
		}

		public Object getData() {
			return data;
		}

		public Object getSource() {
			return source;
		}

		public void preventDefault() {
			this._preventDefault = true;
		}

	}

	/**
	 * Helper to dispatch events for classes  
	 * 
	 * @author hushunjie
	 */
	public static class EventDispatcherHelper implements IEventDispatcher {
		private ArrayList<EventAndListenerPair> listeners = new ArrayList<EventAndListenerPair>();

		public void addEventListener(String event, IEventListener e) {
			listeners.add(new EventAndListenerPair(event, e));
		}

		public void dispatch(Event e) {
			for (int i = 0; i < listeners.size(); i++) {

				if (e._preventDefault)
					break;

				if (i < listeners.size()) {
					EventAndListenerPair p = (EventAndListenerPair) listeners
							.get(i);
					if (p.a.equals(e.getEventName())) {
						p.e.onEvent(e);
					}
				}
			}
		}

		public void dispatch(String eventName, Object object) {

			Event e = new Event(eventName, object);
			this.dispatch(e);

		}

		/*
		 * Dispose this object
		 */
		public void dispose() {

			this.listeners.clear();
			 
		}
	}

	private static class EventAndListenerPair {
		private String a;
		private IEventListener e;

		public EventAndListenerPair(String a, IEventListener e) {
			this.a = a;
			this.e = e;
		}
	}

}